
var express = require('express');
var router = express.Router();
var connection = require('../mysql')
const { packRes } = require("../utils/packRes");





// GET request to retrieve all comments with a specific parentid from comment table with pagination
router.get('/detail', function (req, res, next) {
  var parentid = req.query.parentid;
  var limit = parseInt(req.query.limit) || 5;
  var page = parseInt(req.query.page) || 1;
  var offset = (page - 1) * limit;
  connection.query('SELECT COUNT(*) as total FROM comment', function (error, results, fields) {
    if (error) throw error;
    const total = results[0].total;
    console.log(11111111,results)
    connection.query('UPDATE article SET browsecount = browsecount + 1 WHERE id = ?', [parentid], function (error, results, fields) {
      if (error) throw error;
    });
    connection.query('SELECT * FROM comment WHERE parentid = ? LIMIT ? OFFSET ?', [parentid, limit, offset], function (error, results, fields) {
      if (error) throw error;
      res.status(200).send(packRes(200, { total, limit, page, results }));
    });
  });
});






// POST request to add a comment to comment table
router.post('/', function (req, res, next) {
  var content = req.body.content;
  var parentid = req.body.parentid;
  var userid = req.body.userid;
  var username = req.body.username;
  var nickname = req.body.nickname;
  var otherid = req.body.otherid;
  var otheruser = req.body.otheruser;
  var othernick = req.body.othernick;
  var like = 0;
  let time = new Date().toISOString().slice(0, 19).replace('T', ' ');
  if (!userid) {
    res.status(200).send(packRes(400, '', '请先登录再添加评论'));

  } else if (!parentid) {
    res.status(200).send(packRes(400, '', '需要父级 ID'));

  } else {
    connection.query('INSERT INTO comment (time,content, parentid, userid, username, nickname, otherid, otheruser, othernick, `like`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?,?)', [time, content, parentid, userid, username, nickname, otherid, otheruser, othernick, like], function (error, results, fields) {
      if (error) throw error;
      res.status(200).send(packRes(200, '评论添加成功'));
    });
  }
});



// POST request to delete a comment from comment table
router.post('/delete', function (req, res, next) {
  var id = req.body.id;
  connection.query('DELETE FROM comment WHERE id = ?', [id], function (error, results, fields) {
    if (error) throw error;
    res.status(200).send(packRes(200, '删除成功'));
  });
});




// POST request to like a comment from comment table
router.post('/like', function (req, res, next) {
  var id = req.body.id;
  connection.query('UPDATE comment SET `like` = `like` + 1 WHERE id = ?', [id], function (error, results, fields) {
    if (error) throw error;
    res.status(200).send(packRes(200, '点赞成功'));
  });
});



module.exports = router;


